import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM, GAME_TYPE_ENUM } from "../base/EnumIndex";
import { Tools } from "../common/Tools";
import { AudioManager } from "../manager/AudioManager";
import { EventManager } from "../manager/EventManager";
import { NetworkManager } from "../manager/NetworkManager";
import { ResManager } from "../manager/ResManager";
import { UIManager } from "../manager/UIManager";
import { AdBase } from "./AdBase";
import { AdManager } from "./AdManager";
const ks = window['ks'];
/** 快手广告类 */
export class AdManager_KS extends AdBase {
    static get ins() {
        return super.getInstance<AdManager_KS>();
    }
    gameName: string = "文字我服了";
    /** appID */
    app_id: string = "ks711850216814991072";
    /** bannerID */
    ad_banner_id: string = "adunit-64d55f82495fec1d";
    /** 插屏ID */
    ad_inter_id: string = "2300003749_02";
    /** 激励ID */
    ad_video_id: string = "2300004063_01";

    /**直投项目id(当点击广告进来时和clickid一起拿到)*/
    projectId: string = null;
    /**广告id(当点击广告进来时和clickid一起拿到) */
    promotionId: string = null;
    /**直投参数 */
    cliKey: string = null;

    /**用户openId */
    openId: string = null;
    /**快手广告主id */
    advertiser_id: number = null;

    /** 微信免费广告次数 */
    private freeAdNum: number = 0;

    /**免费解锁次数 */
    private freeUnlockNum: number = 0;
    /**免费提示次数 */
    private freeTipNum: number = 0;

    /** 加载或者初始化所有广告 */
    loadAllAd() {

        switch (this.gameType) {
            case GAME_TYPE_ENUM.WEN_ZI_WO_FU_LE:
                // this.ad_video_id = "2300005917_01";
                // this.gameName = "整活大行家";
                // this.gameId = 14;
                // this.queryGameType = 3;
                // this.ad_video_id = "2300007031_01";
                // this.gameName = "文字我服了";
                // this.gameId = 19;
                // this.queryGameType = 3;
                // this.ad_video_id = "2300007832_01";
                // this.gameName = "炒菜我最狂";
                // this.gameId = 30;
                // this.queryGameType = 3;
                this.ad_video_id = "2300008751_01";
                this.gameName = "秃然的脑洞";
                this.gameId = 41;
                this.queryGameType = 3;
                break;
            case GAME_TYPE_ENUM.NAO_DONG_TIAN_HUA_BAN:
                this.ad_video_id = "2300004063_01";
                this.gameName = "老六我服了";
                this.gameId = 0;
                this.queryGameType = 0;
                // this.ad_video_id = "2300007821_01";
                // this.gameName = "脑洞天花板";
                // this.gameId = 29;
                // this.ad_video_id = "2300008162_01";
                // this.gameName = "真是大聪明";
                // this.gameId = 35;
                // this.queryGameType = 3;
                break;
            case GAME_TYPE_ENUM.WO_YAO_BIAN_TU_LE:
                // this.ad_video_id = "2300004689_01";
                // this.gameName = "梗图来找茬";
                // this.gameId = 15;
                // this.ad_video_id = "2300005918_01";
                // this.gameName = "这波我很秀";
                // this.gameId = 18;
                // this.ad_video_id = "2300007423_01";
                // this.gameName = "谐音梗传";
                // this.gameId = 26;
                // this.queryGameType = 3;
                // this.ad_video_id = "2300008750_01";
                // this.gameName = "脑力秀起来";
                // this.gameId = 40;
                // this.queryGameType = 3;
                this.ad_video_id = "2300008752_01";
                this.gameName = "看我来整活";
                this.gameId = 42;
                this.queryGameType = 3;
                break;
            case GAME_TYPE_ENUM.Zui_Qiang_Zhe_Mo:
                this.ad_video_id = "2300007365_01";
                this.gameName = "最强折磨";
                this.gameId = 24;
                this.queryGameType = 3;
                break;
            case GAME_TYPE_ENUM.WAN_DAN_ZHANG_NAO_ZI_LE:
                // this.ad_video_id = "2300007420_01";
                // this.gameName = "我要上岸";
                // this.gameId = 23;
                // this.queryGameType = 3;
                // this.ad_video_id = "2300007422_01";
                // this.gameName = "谐音大湿";
                // this.gameId = 25;
                // this.queryGameType = 3;
                break;
        }

        AdManager.gameId = this.gameId;
        AdManager.queryGameType = this.queryGameType;
        this.initFreeAds();
        this.initFreeUnlockNum();
        this.initFreeTipNum();

        this.sysInfo = ks.getSystemInfoSync();
        // this.initBanner();
        this.initVideoAd();

        /** 获取启动参数 */
        var options = ks.getLaunchOptionsSync();
        console.log("options:", options);
        if (options.query["callback"]) {
            this.clickID = options.query["callback"];
            AdManager.clickID = this.clickID;
            this.projectId = options.query["campaign_id"] || null;
            AdManager.projectId = this.projectId;
            this.promotionId = options.query["promotionid"] || null;
            AdManager.promotionId = this.promotionId;
            this.cliKey = options.query["ad_id"] || null;
            AdManager.cliKey = options.query["ad_id"];
            this.advertiser_id = options.query["account_id"] || null;
            AdManager.advertiser_id = options.query["account_id"];
            // Tools.setStorage("juLiangClickID",this.clickID);
        } else {
            // this.clickID = Tools.getStorage("juLiangClickID");
        }

        let self = this;
        ks.login({
            success(res) {
                console.log("login 调用成功", res);
                self.code = res.code;
                if (self.gameId != 0) {
                    NetworkManager.getOpenId(self.gameId, self.queryGameType, self.code, (openId) => {
                        self.openId = openId;
                        NetworkManager.reportGameTime(self.gameId, openId, 1, self.clickID, self.queryGameType, self.projectId, self.advertiser_id);
                    });
                }
            },
            fail(res) {
                console.log("login 调用失败", res);
            },
        });

        /**监听小游戏隐藏到后台的事件。锁屏、按 HOME 键退到桌面等操作会触发此事件。 */
        if (this.gameId != 0) {
            ks.onHide(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 2, self.clickID, self.queryGameType, self.projectId, self.advertiser_id);
            });
            ks.onShow(() => {
                NetworkManager.reportGameTime(self.gameId, self.openId, 1, self.clickID, self.queryGameType, self.projectId, self.advertiser_id);
            })
        }

    };
    /** 初始化加载 视频广告 */
    private initVideoAd() {
        let self = this;
        this.ad_video = ks.createRewardedVideoAd({
            adUnitId: self.ad_video_id,
        });

        this.ad_video.onLoad(() => {
            console.log("视频广告加载完成!");
        });
        this.ad_video.load();

        this.ad_video.onClose((res: any) => {
            if (res.isEnded) {
                console.log("获取奖励")
                this.finishVideo();
            } else {
                console.log("没有观看完毕--");
                this.showModal("未观看完视频", "观看完视频才能获得奖励哦", () => {
                    this.showVideoAd(this.videoBack, this.errorBack)
                }, () => {
                    this.errorVideo();
                });
            }
            if (res.count) {
                //在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
                //判断观看了几次广告
            }
        });
    };
    /** 初始化加载 banner */
    private initBanner() {
        let bannerData = {
            left: this.sysInfo.screenWidth,//广告位区域左上角横坐标
            top: this.sysInfo.screenHeight,//广告位区域左上角纵坐标
            width: this.sysInfo.screenWidth,//广告位区域宽度
        }

        this.ad_banner = ks.createBannerAd({
            adUnitId: this.ad_banner_id,
            adIntervals: 20,
            style: bannerData,
        });
    };
    /** 显示Banner广告 */
    public showBanner() {
        if (!this.ad_banner) {
            this.initBanner();
            // return;
        };

        if (this.ad_banner.show) {
            this.ad_banner.show();
        }

        this.ad_banner.onLoad(() => {
            this.ad_banner.show().then(() => {
                console.log("广告显示成功");
            }).catch((err: any) => {
                console.log("广告组件出现问题", err);
                this.ad_banner = null;
            });
        });
    };
    /** 隐藏Banner广告 */
    public hideBanner() {
        if (!this.ad_banner) { return; }
        this.ad_banner.hide();
    };
    /** 播放插屏广告 */
    public showIntersAd() {
        let self = this;
        let interstitialAd = ks.createInterstitialAd({
            adUnitId: self.ad_inter_id,
        });

        interstitialAd.show().then(() => {
            console.log("插屏广告展示成功");
        });
        console.log("showIntersAd");
    }
    /** 播放视频广告  成功回调   失败回调 */
    public showVideoAd(finishBack?: Function, errorBack?: Function, countNum?: number, freeType: number = -1) {
        this.videoBack = null;
        this.errorBack = null;
        if (finishBack) {
            this.videoBack = finishBack;
        } if (errorBack) {
            this.errorBack = errorBack;
        }

        if (this.freeAdNum > 0) {
            this.addFreeAds(-1);
            if (this.videoBack) {
                this.videoBack();
            }
            return;
        }

        if (freeType === 1) { //解锁关卡
            if (this.freeUnlockNum > 0) {
                this.addFreeUnlockNum(-1);
                if (this.videoBack) {
                    this.videoBack();
                }
                return;
            }
        }

        if (freeType === 2) { //关卡提示
            if (this.freeTipNum > 0) {
                this.addFreeTipNum(-1);
                if (this.videoBack) {
                    this.videoBack();
                }
                return;
            }
        }

        if (!this.ad_video) {
            this.initVideoAd();
        }

        this.ad_video.show().then(() => {
            console.log("广告显示成功");
        }).catch((err: any) => {
            this.errorVideo();
            console.log("广告组件出现问题", err);
            // 再手动加载一次
            this.ad_video.load().then(() => {
                console.log("手动加载成功");
                this.ad_video.show();  // 加载成功后需要再显示广告
            });
        });
    }
    /** 视频播放完成 */
    finishVideo() {
        AudioManager.resumeMusic();
        if (this.videoBack) {
            this.videoBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    }
    /** 视频播放失败 isOut 是否中途退出*/
    errorVideo() {
        AudioManager.resumeMusic();
        if (this.errorBack) {
            this.errorBack();
        }
        this.videoBack = null;
        this.errorBack = null;
    };
    /** 开始录屏 */
    createVideoScreen() {
        if (this.videoTimer !== null) {
            clearTimeout(this.videoTimer);
            this.videoTimer = null;
        }
        let self = this;

        this.recorder = ks.getGameRecorder();
        this.recorder.on("start", (s: any) => {
            console.log("开始录屏:", s);
        });
        this.recorder.on("error", (s: any) => {
            console.log("录屏错误:", s);
        });
        this.recorder.start({
            duration: 300
        });

        this.videoTimer = setTimeout(() => {
            self.stopVideoScreen();
        }, 1000 * 280);  //280s 后停止录屏
    };
    /** 停止录屏 */
    stopVideoScreen() {
        console.log('停止录屏');
        if (this.videoTimer !== null) {
            clearTimeout(this.videoTimer);
            this.videoTimer = null;
        }
        let self = this;

        console.log(this.recorder)
        if (!this.recorder || !this.recorder.stop) { return; }
        this.recorder.on("stop", (res: any) => {
            if (res && res.videoID) {
                // 当录制成功时，会产生一个videoID，用于发布录屏(recorder.publishVideo)接口使用
                console.log(`videoID is ${res.videoID}`)
                console.log(`录屏停止，录制成功`)
                self.videoPath = res.videoID;
            } else {
                /****注意：没有videoID时不可展示分享录屏按钮，审核会过此case****/
                /****测试方法：点击右上角"..."按钮打开设置页面，关闭录屏开关，录屏不会产生videoID****/
                // 没有videoID时，可以通过onError回调获取录制失败的原因
                console.log(`录屏停止，录制失败`)
            }

        });


        this.recorder.stop();
    };
    /** 分享视频 */
    shareScreenVideo() {
        let self = this;
        this.recorder.publishVideo({
            video: self.videoPath,
            callback: (error: any) => {
                if (error != null && error != undefined) {
                    console.log("分享录屏失败: " + JSON.stringify(error));
                    return;
                }
                console.log("分享录屏成功");
                EventManager.ins.emit(EVENT_NAME_ENUM.SHARE_SUCESS);  //抛出分享成功的事件
            }
        });
        console.log("shareScreenVideo")
    };
    /** 分享视频   shareTitle 分享内容  imgUrl 分享图路径 resource下的 */
    async shareFriends(shareTitle?: string, imgUrl: string = "share") {
        shareTitle = shareTitle || this.gameName;
        let asset = await ResManager.ins.loadRes("texture/share", cc.Asset, BUNDLE_TYPE_ENUM.MAIN);
        ks.shareAppMessage({
            title: shareTitle,
            imageUrl: asset.url,
            success(res) {
                console.log("分享成功:", res);
                return;
            },
            fail(res) {
                // 转发失败
                console.log("失败原因:", res);
                ks.showToast({
                    title: '分享失败',
                    icon: 'none',
                    duration: 1500//持续的时间
                })
                return;
            }
        });
    };
    /** 添加更多游戏 */
    showMoreGame() {
        setTimeout(() => {
            ks.showGridGamePanel({
                query: {   //Json 格式
                    '花花僵尸': 'ttd12aa7974e142ca002'
                    // '套个甜甜圈神龙版': 'tt3fa54918a09c3fc802',
                    // '山楂串': 'ttcf15b9a8502cccbb02',
                    // '合成大西瓜原创版': 'tt425534e8dd6e24d1'
                },
                type: 'one',  // 'four', 'two'
                size: 'medium',
                position: {
                    top: this.sysInfo.screenHeight / 2 - 70,
                    left: this.sysInfo.screenWidth - 70,
                },
                fail(res: any) {
                    console.log(res);
                }
            });
        }, 100);
    };
    /** 隐藏更多游戏 */
    hideMoreGame() {
        ks.hideGridGamePanel();
    };

    checkCommonUse(callback: Function) {
        ks.checkCommonUse({
            success(res) {
                console.log(`设为常用查询结果为：${res.isCommonUse}`);
                if (res.isCommonUse) {
                    callback(false);
                } else {
                    callback(true);
                }
                return;
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("设为常用查询失败", err.msg);
                }
                callback(false);
                return;
            },
        })
    }

    addCommonUse(callback: Function) {
        let self = this;
        ks.addCommonUse({
            success() {
                console.log("设为常用成功");
                self.addFreeUnlockNum(1);
                UIManager.ins.showToast("恭喜获得解锁卡x1~")
                callback();
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("设为常用失败", err.msg);
                }
            },
        });
    }

    /** 添加桌面功能 */
    addTable(callB: Function) {
        ks.addShortcut({
            success: function (res: any) {
                console.log("添加桌面成功！" + res);
                callB();
                Tools.setStorage('ksaddShortcut', true);
            },
            fail: function (res: any) {
                console.log("添加桌面失败！" + res);
            }
        });
    }
    /** 是否已经添加过桌面了 */
    isAddTable(callB: Function) {
        if (cc.sys.os === cc.sys.OS_ANDROID) {
            //仅 Android 支持
            ks.checkShortcut({
                success: function (res: any) {
                    console.log("是否已添加快捷方式", res.installed);
                    callB(!res.installed);
                },
                fail: function (err: any) {
                    if (err.code === -10005) {
                        console.log("暂不支持该功能");
                    } else {
                        console.log("检查快捷方式失败", err.msg);
                    }
                    callB(true);
                }
            });
        } else {
            let isAdd = Tools.getStorage('ksaddShortcut');
            callB(!isAdd);
        }
    }
    /** 弹框  确定或者取消 */
    showModal(titleStr: string, infoStr: string, finishBack?: any, cancelBack?: any) {
        ks.showModal({
            title: titleStr,
            content: infoStr,
            success(res: any) {
                if (res.confirm) {
                    if (!finishBack) { return; }
                    finishBack();
                    console.log("showModal, 确定");
                } else if (res.cancel) {
                    if (!cancelBack) { return; }
                    cancelBack();
                    console.log("showModal, 取消");
                }
            },
            fail(res: any) {
                console.log(`showModal调用失败` + res);
            },
        });
    }

    /** 复访相关初始化 */
    private initFreeAds() {
        this.freeAdNum = Tools.getStorage("freeAdNum");
        if (this.freeAdNum === null) {
            this.freeAdNum = 0;
        }
        // console.log("复访", this.fuFangFinished, this.freeAdNum)
    }

    /**签到 */
    public sign(num) {
        this.freeAdNum = Tools.getStorage("freeAdNum");
        this.addFreeAds(num);
    }

    /**签到2 */
    public sign2(num: any[]) {
        let type = num[0];
        if (type == 1) {//解锁关卡
            this.freeUnlockNum = Tools.getStorage("freeUnlockNum");
            this.addFreeUnlockNum(num[1]);
        } else if (type == 2) {//提示
            this.freeTipNum = Tools.getStorage("freeTipNum");
            this.addFreeTipNum(num[1]);
        } else {
            this.freeAdNum = Tools.getStorage("freeAdNum");
            this.addFreeAds(num[1]);
        }
    }

    /**初始化解锁次数 */
    private initFreeUnlockNum() {
        this.freeUnlockNum = Tools.getStorage("freeUnlockNum");
        if (this.freeUnlockNum === null) {
            this.freeUnlockNum = 0;
        }
    }

    /**初始化提示次数 */
    private initFreeTipNum() {
        this.freeTipNum = Tools.getStorage("freeTipNum");
        if (this.freeTipNum === null) {
            this.freeTipNum = 0;
        }

    }

    /** 添加免解锁次数 */
    private addFreeUnlockNum(num: number) {
        this.freeUnlockNum += num;
        Tools.setStorage("freeUnlockNum", this.freeUnlockNum);
    }

    /** 添加免提示次数 */
    private addFreeTipNum(num: number) {
        this.freeTipNum += num;
        Tools.setStorage("freeTipNum", this.freeTipNum);
    }

    /** 添加免视频广告次数 */
    private addFreeAds(num: number) {
        this.freeAdNum += num;
        Tools.setStorage("freeAdNum", this.freeAdNum);
        // console.log("addFreeAds", this.freeAdNum)
    }


    /** 震动 */
    vibrate(num: number) {
        if (num >= 15) {
            ks.vibrateLong({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateLong调用失败:` + res); },
            });
        } else {
            ks.vibrateShort({
                success(res: any) { console.log(res) },
                fail(res: any) { console.log(`vibrateShort调用失败:` + res); },
            });
        }
    }
    exit() {
        ks.exitMiniProgram()
    }
}